import Schema from 'validate'
// 手机号码的验证
const mobileValidate = new Schema({
  mobile: {
    type: String,
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '手机号码不合法'
  }
})
// 定义变量保存验证码
// code 验证
const codeValidate = new Schema({
  type: String,
  required: true,
  match: /^\d{6}$/,
  message: 'code不合法'
})
// let secret_code = ''
Page({
  data: {
    countDownVisible: false,
    mobile: "18794584055",
    timeData: null,
    code: '',


  },
  // 倒计时
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 验证手机号码
  // verifyMobile() {
  //   const reg = /^[1][3-8][0-9]{9}$/
  //   // 正则验证（去除两端空格）
  //   const valid = reg.test(this.data.mobile.trim())
  //   if (!valid) wx.utils.toast("请输入正确的手机号码")
  //   // 返回验证结果
  //   return valid
  //   // 获取短信验证码

  // },
  async getCode() {

    const mobile = this.data.mobile
    const errs = mobileValidate.validate({ mobile: mobile })
    // console.log(4443, errs);
    if (errs.length) {
      return wx.utils.toast(errs[0].message)
    }

    const res = await wx.http({
      url: '/code',
      data: { mobile }
    })
    console.log(res);
    this.setData({
      countDownVisible: true,
      code: res.data.code,
    })

  },

  onLoad({ redirectURL }) {
    this.redirectURL = redirectURL
  },
  async submitForm() {
    console.log(11);
    const { mobile, code } = this.data
    // const mobile = this.data.mobile
    const errs = mobileValidate.validate({ mobile: mobile })
    // console.log(4443, errs);
    if (errs.length) {
      return wx.utils.toast(errs[0].message)
    }

    const codeErrs = codeValidate.validate({ code: code })
    // console.log(4443, errs);
    if (codeErrs.length) {
      return wx.utils.toast(errs[0].message)
    }

    const res = await wx.http.post('/login', { mobile, code })
    console.log(res);
    const app = getApp()
    app.setToken(res.data.token, res.data.refreshToken)

    if (this.redirectURL) {
      wx.reLaunch({ url: '/' + this.redirectURL })
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    }
  }



})
